package com.ellricky.baselib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.andr.common.util.ScreenUtil;
import com.ellricky.baselib.R;

public class ESeekBarView extends RelativeLayout implements SeekBar.OnSeekBarChangeListener {
    private Context context;

    private TextView tvKey;
    private TextView tvSeekRate;
    private SeekBar seekBar;


    public ESeekBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

        View.inflate(context, R.layout.base_layout_seek_bar, this);
        tvKey = findViewById(R.id.tvKey);
        tvSeekRate = findViewById(R.id.tvSeekRate);
        seekBar = findViewById(R.id.seekBar);

        seekBar.setOnSeekBarChangeListener(this);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ESeekBarView);

        String key = typedArray.getString(R.styleable.ESeekBarView_base_seek_bar_key);
        setKey(key);

        typedArray.recycle();
    }

    public void setKey(String key) {
        if (TextUtils.isEmpty(key)) tvKey.setVisibility(GONE);
        else {
            tvKey.setVisibility(VISIBLE);
            tvKey.setText(key);
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //进度是从-50~50的,但是seekbar.getmin()有限制,所以这里用0~100 -50;
        //设置文本显示
        tvSeekRate.setText(String.format("%s%%", String.valueOf(progress)));

        //获取文本宽度
        float textWidth = tvSeekRate.getWidth();

        //获取seekbar最左端的x位置
        float left = seekBar.getLeft();

        //进度条的刻度值
        float max = Math.abs(seekBar.getMax());

        //这不叫thumb的宽度,叫seekbar距左边宽度,实验了一下，seekbar 不是顶格的，两头都存在一定空间
        // ，所以xml 需要用paddingStart 和 paddingEnd 来确定具体空了多少值,我这里设置15dp;
        float thumb = ScreenUtil.dpUnit(context, 20);

        //每移动1个单位，text应该变化的距离 = (seekBar的宽度 - 两头空的空间) / 总的progress长度
        float average = (((float) seekBar.getWidth()) - 2 * thumb) / max;

        //int to float

        //textview 应该所处的位置 = seekbar最左端 + seekbar左端空的空间 + 当前progress应该加的长度 - textview宽度的一半(保持居中作用)
        float pox = left - textWidth / 2 + thumb + average * (float) progress;
        tvSeekRate.setX(pox);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    public void setRate(int rate) {
        seekBar.setProgress(rate);
    }

    public String getRate() {
        return tvSeekRate.getText().toString().trim();
    }
}
